<?php


namespace app\app\controller;


use app\constant\OrderConst;
use app\model\AdminOrder;
use app\model\AdminOrderItem;
use app\model\AppComment;
use app\util\ReturnCode;
use think\Db;
use think\exception\DbException;

class Comment extends Base
{
    /**
     * 发布评价
     */
    public function pub()
    {
        $post = $this->request->post();
        if (!isset($post['order_id'])) {
            return $this->buildFailed(ReturnCode::INVALID, '无效的参数');
        }
        if (!isset($post['content']) || empty($post['content'])) {
            return $this->buildFailed(ReturnCode::INVALID, '缺少评价内容');
        }
        if (!isset($post['rate']) || empty($post['rate'])) {
            return $this->buildFailed(ReturnCode::INVALID, '请打分');
        }
        $orderId = $post['order_id'];
        $model = AdminOrder::get($orderId, null, true);
        if (!$model) {
            return $this->buildFailed(ReturnCode::INVALID, '无效的订单');
        }
        if ($model->has_comment == OrderConst::HAS_COMMENT) {
            return $this->buildFailed(ReturnCode::INVALID, '已经发布过评价了');
        }
        if ($model->trade_status != OrderConst::ORDER_STATUS_USED) {
            return $this->buildFailed(ReturnCode::INVALID, '当前订单状态不允许发布评价');
        }
        $where = ['order_id' => $orderId];
        $where = $this->addTid($where);
        $itemModel = AdminOrderItem::get($where);
        if (!$itemModel) {
            return $this->buildFailed(ReturnCode::INVALID, '无效的订单');
        }
        $data = [
            'uid' => $model->uid,
            'rate' => $post['rate'],
            'imgs' => isset($post['imgs']) ? json_encode($post['imgs']) : null,
            'content' => $post['content'],
            'order_id' => $orderId,
            'order_item_id' => $itemModel->id,
            'goods_id' => $model->goods_id,
            'goods_title' => $itemModel->goods_title,
            'sku_title' => $itemModel->sku_title];
        $data = $this->addTid($data);
        Db::transaction(function () use ($model, $data) {
            AppComment::create($data);
            $model->setAttr('has_comment', OrderConst::HAS_COMMENT);
            $model->allowField(true)->save();
        });
        return $this->buildSuccess(null);
    }

    /**
     * 获取评价列表
     */
    public function getList()
    {
        $goodsId = $this->request->param('goods_id');
        if (!isset($goodsId)) {
            return $this->buildFailed(ReturnCode::INVALID, '无效的参数');
        }
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $obj = new AppComment();
        $where = ['goods_id' => $goodsId, 'del' => 0];
        $where = $this->addTid($where);
        $listObj = $obj->getList($limit, $start, $where);
        return $this->buildSuccess([
            'list' => $listObj['list'],
            'count' => $listObj['count']
        ]);
    }


}